<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use League\Flysystem\Exception;
use ToolClass\SendEmailClass;
use ServiceClass\User;

class UserController extends Controller
{
    //
    public function __construct(User $user)
    {
        $this->user  = $user;
    }

    public function sendRegisterEmail(Request $request){
        try{
            $Email = $request->input('email');
            $check = DB::table('user')->where('user_email','=',$Email)->get();
            if($check){
                return json_encode(['msg' => '账号已注册']);
            }
            $verifyCode = sendEmailClass::sendRegisterEmail($Email);
            DB::table('verify')->where('verify_email' ,'=' , $Email)->delete();
            DB::table('verify')->insert(['verify_email' => $Email,'verify_code' => $verifyCode]);

            return json_encode(['msg' => '发送成功']);

        }catch (Exception $e){

            echo $e->getMessage().'failed line:'.$e->getLine().'failed string:'.$e->getTraceAsString();
            exit;
        }

    }

    public function register(Request $request){
        try{
            $Email = $request->input('email');
            $verifyCode   = $request->input('verifyCode');
            $nickName    = $request->input('nickName');
            $password   =  md5($request->input('password'));

            $check = DB::table('user')->where('user_email','=',$Email)->get();
            if($check){
                return json_encode(['msg' => '账号已注册']);
            }
            $result = DB::table('verify')->where('verify_email','=',$Email)->where('verify_code','=',$verifyCode)->get();
            if($result){

                DB::table('user')->insert(['user_email' => $Email,'user_nickname' => $nickName,'user_password' => $password]);

                return json_encode(['msg' => '登录成功']);

            }else{
                return json_encode(['msg' => '验证码错误']);
            }


        }catch ( Exception $e){
            echo $e->getMessage().'failed line:'.$e->getLine().'failed string:'.$e->getTraceAsString();
            exit;
        }
    }

    public function login(Request $request){
        try{
            $Email = $request->input('email');
            $password = md5($request->input('password'));

            $result = DB::table('user')->where('user_email','=',$Email)->where('user_password','=',$password)->get();
            if($result){
                return json_encode(['msg' => '登录成功']);
            }else{
                return json_encode(['msg' => '登录失败']);
            }
        }catch (Exception $e){
            echo $e->getMessage().'failed line:'.$e->getLine().'failed string:'.$e->getTraceAsString();
            exit;
        }
    }
}
